package com.shanghaionstar.login.register;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.common.util.PreferencesUtls;
import com.onstar.cn.framework.annotation.ContentView;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.annotation.OnClick;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.mag.joinme.RegisterRequestEntity;
import com.onstar.cn.mag.joinme.RegisterResponseEntity;
import com.onstar.cn.weight.DeleteEditText;
import com.onstar.cn.weight.TimeButton;
import com.shanghaionstar.R;
import com.shanghaionstar.login.register.iview.IRegisterVisitorView;
import com.shanghaionstar.login.register.presenter.RegisterVisitorPresenter;
import com.shanghaionstar.swipe.SwipeActivity;
import com.shanghaionstar.user.TermsConditionsActivity;
import com.shanghaionstar.utils.AlertDialogUtil;
import com.shanghaionstar.utils.FinalConstants;
import com.shanghaionstar.utils.JoinMeConstants;
import com.shanghaionstar.weight.CommonInputLayout;
import com.shanghaionstar.weight.CommonProgressButton;

/**
 * Created by 7828wc on 16/7/4.
 */
@ContentView(R.layout.joinme_register_visitor)
public class RegisterVisitorActivity extends SwipeActivity implements IRegisterVisitorView {
    private RegisterVisitorPresenter presenter;
    @FindViewById
    private TextView apply_xieyi;
    @FindViewById
    private CommonInputLayout et_user_name, et_user_pass, et_user_mail, et_verify_code;
    @FindViewById
    private TimeButton btn_get_code;
    @FindViewById
    private CommonProgressButton btn_submit;

    private boolean isShowPassword = false;
    private boolean isGetCode = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        apply_xieyi.setText(Html.fromHtml("<font color='#9c9da0' size='24px'>"
                + getResources().getString(R.string.read_check) + "</font><font color='#000000' size='24px'>"
                + getResources().getString(R.string.xieyi2) + "</font><font color='#9c9da0' size='24px'>"
                + getResources().getString(R.string.xieyi3) + "</font>"));

        presenter = new RegisterVisitorPresenter(getScheduler());
        presenter.setView(this);

        et_user_pass.isShowPassword(isShowPassword);
        et_user_pass.setRightIconClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                et_user_pass.isShowPassword(!isShowPassword);
                isShowPassword = !isShowPassword;
            }
        });
        setListener();
    }

    private void setListener() {
        et_user_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFoucus) {
                if (!hasFoucus) {
                    presenter.verifyUserName(et_user_name, true);
                } else verifyResult(et_user_name, FinalConstants.Register.CHECK_CANCEl);
                setEditTextDelVisible((DeleteEditText) view, hasFoucus);
            }
        });
        et_user_pass.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFoucus) {
                if (!hasFoucus) {
                    presenter.verifyUserPass(et_user_pass, et_user_name.getText());
                }
                setEditTextDelVisible((DeleteEditText) view, hasFoucus);
            }
        });
        et_user_mail.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFoucus) {
                if (!hasFoucus) {
                    presenter.verifyEmailOrPhone(et_user_mail, true);
                } else verifyResult(et_user_mail, FinalConstants.Register.CHECK_CANCEl);
                setEditTextDelVisible((DeleteEditText) view, hasFoucus);
            }
        });
        btn_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (presenter.verifyUserName(et_user_name, false) && presenter.verifyEmailOrPhone(et_user_mail, false) && presenter.verifyUserPass(et_user_pass, et_user_name.getText()) && presenter.verifyCode(et_verify_code)) {
                    isGetCode = false;
                    registerVisitor(JoinMeConstants.OperationType.CHECKREGCODE);
                }
            }
        });

        btn_get_code.setResultListener(new TimeButton.ResultListener() {
            @Override
            public void end() {
                enable(true);
            }
            @Override
            public void inProgress() {
            }
        });
    }

    private void enable(boolean enabled) {
        et_user_name.setEditEnabled(enabled);
        et_user_mail.setEditEnabled(enabled);
        et_user_pass.setEditEnabled(enabled);
    }


    private void setEditTextDelVisible(DeleteEditText view, boolean b) {
        DeleteEditText deleteEditText = view;
        deleteEditText.hasFocus(b);
        deleteEditText.setDeleteIconVisible(b && deleteEditText.getText().length() > 0);
    }

    @OnClick({R.id.btn_get_code,R.id.apply_xieyi})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_get_code:
                if (presenter.verifyUserName(et_user_name, false) && presenter.verifyEmailOrPhone(et_user_mail, false) && presenter.verifyUserPass(et_user_pass, et_user_name.getText())) {
                    btn_get_code.setVisibility(View.GONE);
                    enable(false);
                    isGetCode = true;
                    registerVisitor(JoinMeConstants.OperationType.INVOKEREGCODE);
                }
                break;
            case R.id.apply_xieyi:
                startActivity(new Intent(this, TermsConditionsActivity.class));
                break;
            default:
                break;
        }
    }

    private void registerVisitor(JoinMeConstants.OperationType operationType) {
        RegisterRequestEntity registerRequestEntity = new RegisterRequestEntity();
        registerRequestEntity.setUserName(et_user_name.getText());
        registerRequestEntity.setPassWord(et_user_pass.getText());
        if (CommonUtil.isEmail(et_user_mail.getText())) {
            registerRequestEntity.setEmailAddress(et_user_mail.getText());
            registerRequestEntity.setMobilePhoneNumber("");
        } else {
            registerRequestEntity.setEmailAddress("");
            registerRequestEntity.setMobilePhoneNumber(et_user_mail.getText());
        }
        if (!isGetCode) {
            registerRequestEntity.setSecCode(et_verify_code.getText().toString());
        }
        presenter.registerVisitor(registerRequestEntity, operationType.getOperationType());
        presenter.start();
    }

    @Override
    public void verifyResult(View view, int errorResId) {
        if (view instanceof CommonInputLayout) {
            CommonInputLayout inputLayout = (CommonInputLayout) view;
            inputLayout.setEnabled(true);
            if (errorResId == FinalConstants.Register.NO_ERROR) {
                inputLayout.setCheckHintText(null);
            } else if (errorResId == FinalConstants.Register.CHECK_OK) {
                inputLayout.showLoading(false);
                inputLayout.setRightIcon(R.drawable.onstar_joinme_check_ok);
            } else if (errorResId == FinalConstants.Register.CHECK_CANCEl) {
                inputLayout.setRightIcon(-1);
                inputLayout.showLoading(false);
            } else if (errorResId == FinalConstants.Register.SHOW_LOADING) {
                inputLayout.showLoading(true);
            } else {
                inputLayout.setCheck(false);
                inputLayout.setCheckHintText(errorResId);
            }
        }
    }

    @Override
    public void setLoading(boolean isLoading) {
        if (isGetCode) {
            verifyResult(et_verify_code, isLoading ? FinalConstants.Register.SHOW_LOADING : FinalConstants.Register.CHECK_CANCEl);
            btn_get_code.setVisibility(View.VISIBLE);
        } else {
            btn_submit.showLoading(isLoading);
        }
    }

    @Override
    public void onResponseError(OnStarException e) {
        if (isGetCode) {
            btn_get_code.setVisibility(View.VISIBLE);
            btn_submit.setEnabled(true);
            enable(true);
        }
        AlertDialogUtil.showDialogByOnstarException(onActivity(),e);
    }

    @Override
    public void onReponseSuccess(RegisterResponseEntity registerResponseEntity) {
        if (registerResponseEntity != null) {
            if ((!CommonUtil.isNull(registerResponseEntity.getIsEmailUnique()) && registerResponseEntity.getIsEmailUnique().equalsIgnoreCase("false")) ||
                    (!CommonUtil.isNull(registerResponseEntity.getIsMobileUnique()) && registerResponseEntity.getIsMobileUnique().equalsIgnoreCase("false"))) {
                et_user_mail.setCheckHintText(R.string.useremail_exist);
            }
            if (!CommonUtil.isNull(registerResponseEntity.getIsMobileUnique()) && registerResponseEntity.getIsMobileUnique().equalsIgnoreCase("false")) {
                et_user_name.setCheckHintText(R.string.username_exist);
            }
        } else {
            et_user_mail.setCheckHintText(R.string.SB022_MSG016);
            return;
        }
        if (isGetCode) {
            btn_submit.setEnabled(true);
            btn_get_code.setVisibility(View.VISIBLE);
            btn_get_code.start(R.string.again_send);
        } else {
//            presenter.sendReport(FunctionNameFindId.RegisterVisitor);
            //Register success
            PreferencesUtls.getInstance(this).putString(FinalConstants.SharedPreferencesConfig.MASKED_USER_NAME, et_user_name.getText());
            PreferencesUtls.getInstance(this).putString(FinalConstants.SharedPreferencesConfig.LOGIN_NAME_KEY, et_user_name.getText());
            AlertDialogUtil.showAlertDialog(this, R.string.dialog_warning, R.string.SB021_28, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    dialogInterface.dismiss();
                    setResult(RESULT_OK);
                    finish();
                }
            });
        }
    }

    @Override
    public Activity onActivity() {
        return this;
    }

    @Override
    public BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        et_user_name.recyle();
        et_user_mail.recyle();
        et_user_pass.recyle();
        et_verify_code.recyle();
    }
}
